
/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup  店铺
 * @api {POST} api/store/create 创建店铺
 * @apiName api/store/create
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/store/create', {
 *    name: '店铺名',
 *    avatar: '店铺头像',
 *    info: '店铺简介',
 *  });
 * @apiHeader {String} authorization 用户登录或注册成功时返回的 token
 * @apiParam {String} name 店铺名
 * @apiParam {String} avatar 店铺头像
 * @apiParam {String} info 店铺简介
 * @apiSuccess (请求成功) {Object} store 店铺数据
 * @apiuse  ErrorResponse
 */

const { query, create } = require('../../helper/db');
const { ok, door } = require('../../helper/util');

module.exports = async ctx => {
  var params = ctx.request.body;
  var token = ctx.headers.authorization;
  var user = await door(token);
  var storelist = await query('select * from store where name = ?', [params.name]);

  if (storelist.length) {
    throw new Error('该商城已存在');
  }

  var store = await create('store', {
    name: params.name,
    avatar: params.avatar,
    info: params.info,
    userid: user.id,
  });

  ctx.body = ok({ store });
}
